import * as React from 'react'
import { Table, Input, Button, Space, Form, InputNumber, Select, message, Popconfirm, Row, Divider, Col, Card } from 'antd';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, PlayCircleOutlined } from '@ant-design/icons';
import MyModal from '../notification-table/my-modal';


export interface DetectItemsProps {
    name?: string;
    searchKeys?: string;
    getMainDataUrl?: string;
    postMainDataUrl?: string;
    putMainDataUrl?: string;
    deleteMainDataUrl?: string;
}


const DetectItems: React.FC<DetectItemsProps> = function ({ name, searchKeys,
    getMainDataUrl, postMainDataUrl, putMainDataUrl, deleteMainDataUrl,
    ...otherProps }) {


    const [searchTerm, setSearchTerm] = React.useState({});
    const [messageApi, contextHolder] = message.useMessage();
    const defaultMainData = [
        {

            "id": 200,
            "code": "I0035",
            "name": "长度",
            "type": "尺寸",
            "tool": null,
            "valType": "浮点数",


        },
        {

            "id": 201,
            "code": "I0036",
            "name": "宽度",
            "type": "尺寸",
            "tool": null,
            "valType": "浮点数",


        },
        {

            "id": 202,
            "code": "I0038",
            "name": "颜色是否纯正",
            "type": "外观",
            "tool": null,
            "valType": "文本",


        },
        {

            "id": 203,
            "code": "I0040",
            "name": "外观照片",
            "type": "外观",
            "tool": null,
            "valType": "文件",


        },
        {

            "id": 204,
            "code": "I0041",
            "name": "检测过程视频",
            "type": "外观",
            "tool": null,
            "valType": "文件",


        },
        {

            "id": 205,
            "code": "I0042",
            "name": "个数清点",
            "type": "外观",
            "tool": null,
            "valType": "整数",


        },
        {

            "id": 206,
            "code": "I0043",
            "name": "合格证编号",
            "type": "外观",
            "tool": null,
            "valType": "文本",


        },
        {

            "id": 207,
            "code": "I0044",
            "name": "功能测试",
            "type": "性能",
            "tool": "自带APP",
            "valType": "文件",


        }
    ]

    const [mainData, setMainData] = React.useState(defaultMainData);
    const [mainPostForm] = Form.useForm()
    const [mainUpdateForm] = Form.useForm()

    const defaultSearchKeys = 'code,name,type,tool';
    let searchKeyList = searchKeys === ''? defaultSearchKeys.split(',').map(item => item.trim()) : searchKeys.split(',').map(item => item.trim());
    //console.log(supportExport)


    //Api方法区 

    //getMainData
    function getMainData(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                setMainData(data.data);
            })
    }

    //postMainData
    function postMainData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '新增成功',
        });
    }
    //putMainData
    function putMainData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '修改成功',
        });
    }
    //putMainData
    function deleteMainData(values: any, url) {
        fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '删除成功',
        });
    }


    //筛选功能
    const handleSearch = () => {
        //这里的查找是字符串包含 如果要完全匹配改成===
        let filteredData = mainData;

        for (var i in searchKeyList) {
            var searchKey = searchKeyList[i];
            if (searchKey === 'id')
                continue;
            if (searchTerm[searchKey]) {
                filteredData = filteredData.filter(item => item[searchKey].includes(searchTerm[searchKey]));
            }
        }
        //console.log(filteredData)
        setMainData(filteredData);
    }
    const resetSearch = () => {
        setSearchTerm({})
        //TODO: setMainData()
    }
    const SearchInput = () => {
        const handleInputChange = (key) => (e) => {
            setSearchTerm(prevState => ({
                ...prevState,
                [key]: e.target.value
            }));
            console.log(key, e.target.value);
        }
        return (
            <>
                <Space size='large'>
                    {searchKeyList.map(key => (
                        <Input
                            placeholder={"请输入" + key}
                            value={searchTerm[key]}
                            onChange={handleInputChange(key)}
                            style={{ width: 200 }}
                        />
                    ))}
                </Space>
            </>
        )
    }

    //主界面表格列
    let mainColumns = []
    let mainColumnsJson = {
        "code": "检测项编码",
        "name": "检测项名称",
        "type": "检测项类型",
        "tool": "检测工具",
        "valType": "检测值类型",
        "action": "操作"

    }

    for (var x in mainColumnsJson) {
        mainColumns.push({
            title: mainColumnsJson[x],
            dataIndex: x,
            key: x
        })
    }
    //自定义操作列渲染
    const targetObject = mainColumns.find(item => item.key === 'action');
    const edit = (record) => {
        mainPostForm.setFieldsValue(record);
        console.log(record);
        updateModalVisibility(0, true);
    }
    const deleteRow = (key) => {
        const newData = mainData.filter((item) => item.id !== key);
        setMainData(newData);

        //TODO Fetch DELETE
    };

    if (targetObject) {
        targetObject.render = (_, record) => {

            return (
                <>
                    <Space size='middle'>
                        <a href="#" onClick={() => edit(record)}><EditOutlined /> 修改</a>
                        <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                            <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                        </Popconfirm>
                    </Space>
                </>
            )


        };
    }

    const statusObject = mainColumns.find(item => item.key === 'status');
    if (statusObject) {
        statusObject.render = (_, record) => {
            if (record.status === 'todo') {
                return (<>待入库</>)
            } else {
                return (<>已完成</>)
            }
        }
    }

    const codeObject = mainColumns.find(item => item.key === 'code');
    if (codeObject) {
        codeObject.render = (_, record) => {
            return (
                <>
                    <a href="#" onClick={() => edit(record)}>{record.code}</a>
                </>
            )
        }
    }

    //console.log('mainColumns: ', mainColumns);



    //对话框
    const [isModalVisible, setIsModalVisible] = React.useState([false, false, false]);

    // 修改第 i 个元素的值
    const updateModalVisibility = (i: number, newValue: boolean) => {
        setIsModalVisible(prevState => {
            // 创建一个新的数组，避免直接修改原数组
            const newArray = [...prevState];
            newArray[i] = newValue; // 修改第 i 个元素
            return newArray;
        });
    };
    const onFinish = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(0, false);
    };
    const submitMainUpdateForm = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(1, false);
    }







    const CustomFormA = () => {
        const ret = (
            <>
                <Form form={mainPostForm} name='mainPostForm' onFinish={onFinish} layout="vertical" labelAlign='left'>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="检测项编号" name="code">
                                <Input placeholder="检测项编号" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="检测项名称" name="name">
                                <Input placeholder="检测项名称" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="检测项类型" name="type">
                                <Select options={[
                                    { value: '外观', label: '外观' },
                                    { value: '性能', label: '性能' },
                                    { value: '尺寸', label: '尺寸' },
                                ]} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="检测工具" name="tool">
                                <Input placeholder="请输入检测工具" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="检测值类型" name="valType">
                            <Select options={[
                                    { value: '浮点数', label: '浮点数' },
                                    { value: '整数值', label: '整数值' },
                                    { value: '文本', label: '文本' },
                                    { value: '文件', label: '文件' },
                                ]} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(0, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" >提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )

        return ret;
    }





    return (
        <>
            {contextHolder}

            <div style={{ marginTop: 20, marginLeft: 20 }}>
                <Space size='large'>
                    <SearchInput />
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={resetSearch}>
                        重置
                    </Button>
                    <Button type="primary" onClick={() => { mainPostForm.resetFields(); updateModalVisibility(0, true) }}>
                        + 新增
                    </Button>
                    {/* 主界面新增对话框 一个Form*/}
                    <MyModal open={isModalVisible[0]} onCancel={() => updateModalVisibility(0, false)}>
                        <CustomFormA />
                    </MyModal>
                </Space>
                <Divider />
                <Row>
                    <Table dataSource={mainData} columns={mainColumns} style={{ width: '100%' }}></Table>
                </Row>
            </div>
        </>
    )

}

DetectItems.displayName = '检测项设置'
export default DetectItems;